package com.pdd.commons.ai;

import com.baidu.aip.ocr.AipOcr;
import com.pdd.config.yml.ApiConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.locks.ReentrantLock;

/**
 * @author:liyangpeng
 * @date:2019/6/4 12:00
 */
@Component
public class BaiduOCR {

    @Autowired
    private ApiConfig apiConfig;

    private AipOcr client=null;

    private ReentrantLock reentrantLock=new ReentrantLock();

    public AipOcr getInstance(){
        if(client==null){
            //此处使用重入锁防止多线程访问生成的对象不是同一个
            reentrantLock.lock();
            try {
                //双重检测
                if(client==null){
                    client=new AipOcr(apiConfig.baiduAPP_Id,apiConfig.baiduAPI_key,apiConfig.baiduSecret_key);
                    client.setConnectionTimeoutInMillis(3000);
                    client.setSocketTimeoutInMillis(6000);
                }
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                //解锁
                reentrantLock.unlock();
            }
        }
        return client;
    }
}